package com.example.yibu.netty.manager;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;

public class LiveRoomHandler extends SimpleChannelInboundHandler<String> {

    private final UserSessionManager userSessionManager = new UserSessionManager();
    private final Map<Integer, Set<String>> roomUsers = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        // 假设msg是JSON字符串，包含roomID和userId
        JSONObject jsonObject = JSONObject.parseObject(msg);
        int roomID = jsonObject.getIntValue("roomID");
        String userId = jsonObject.getString("userId");
        // 将用户加入房间
        roomUsers.computeIfAbsent(roomID, k -> new ConcurrentSkipListSet<>()).add(userId);
        userSessionManager.addUser(userId, ctx);

        // 广播消息给房间内的所有用户
        broadcast(roomID, "User " + userId + " joined the room.");

        // 向客户端回复加入成功的消息
        ctx.writeAndFlush("Joined room successfully.");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 当连接断开时，移除用户
        for (Map.Entry<Integer, Set<String>> entry : roomUsers.entrySet()) {
            entry.getValue().removeIf(userId -> userSessionManager.getUserSession(userId) == ctx);
        }
        userSessionManager.removeUser(ctx.channel().id().asLongText());
    }

    private void broadcast(int roomID, String message) {
        roomUsers.getOrDefault(roomID, Collections.emptySet()).forEach(userId -> {
            ChannelHandlerContext ctx = userSessionManager.getUserSession(userId);
            if (ctx != null) {
                ctx.writeAndFlush(message + "\n");
            }
        });
    }

    public void sendMessageToUser(String userId, String message) {
        ChannelHandlerContext ctx = userSessionManager.getUserSession(userId);
        if (ctx != null) {
            ctx.writeAndFlush(message + "\n");
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 异常处理...
        cause.printStackTrace();
        ctx.close();
    }
}
